package dbops

import (
	_ "database/sql"
	"gitee.com/DengAnbang/Wefore/src/bean"
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/goutils/loge"
	"gitee.com/DengAnbang/goutils/utils"
	"strings"
)

type BaseUser struct {
	UserName     string `json:"user_name"`
	UserId       string `json:"user_id"`
	HeadPortrait string `json:"head_portrait"`
}

func NewBaseUser(data map[string]string) *BaseUser {
	return &BaseUser{
		UserName:     data["name"],
		UserId:       data["user_id"],
		HeadPortrait: data["head_portrait"],
	}
}

type UserBean struct {
	BaseUser
	Account          string               `json:"account"`
	JobNumber        string               `json:"job_number"`
	PhoneNumber      string               `json:"phone_number"`
	CredentialType   string               `json:"credential_type"`
	CredentialNumber string               `json:"credential_number"`
	Structures       *[]StructureTreeBean `json:"structures"`
	Pwd              string               `json:"-"`
}

func (u *UserBean) Modify(new UserBean) {
	if len(new.UserName) != 0 {
		u.UserName = new.UserName
	}
	if len(new.JobNumber) != 0 {
		u.JobNumber = new.JobNumber
	}
	if len(new.PhoneNumber) != 0 {
		u.PhoneNumber = new.PhoneNumber
	}
	if len(new.HeadPortrait) != 0 {
		u.HeadPortrait = new.HeadPortrait
	}
	if len(new.CredentialType) != 0 {
		u.CredentialType = new.CredentialType
	}
	if len(new.CredentialNumber) != 0 {
		u.CredentialNumber = new.CredentialNumber
	}
	if len(new.Pwd) != 0 {
		u.Pwd = new.Pwd
	}
}
func NewUserBean(data map[string]string) *UserBean {
	return &UserBean{
		BaseUser:         *NewBaseUser(data),
		Account:          data["account"],
		JobNumber:        data["job_number"],
		PhoneNumber:      data["phone_number"],
		CredentialType:   data["credential_type"],
		CredentialNumber: data["credential_number"],
		Pwd:              data["pwd"],
	}
}
func UserRegister(userBean UserBean) (UserBean, error) {
	var user UserBean
	if len(userBean.Account) == 0 {
		return user, bean.NewErrorMessage("账号不能为空")
		//return user, httpUtils.NewResultError(code.NormalErr, "账号不能为空")
	}
	if len(userBean.Pwd) == 0 {
		return user, bean.NewErrorMessage("密码不能为空")
	}
	if len(userBean.UserName) == 0 {
		return user, bean.NewErrorMessage("名字不能为空")
	}
	user, err = UserSelect(userBean.Account)
	if len(user.UserId) > 0 {
		return user, bean.NewErrorMessage("用户已经存在了!")
	}
	userBean.UserId = utils.NewUUID()
	stmtIn, err := dbConn.Prepare("INSERT INTO table_user (user_id,account,pwd,name,job_number,head_portrait,credential_type,credential_number,phone_number)VALUES(?,?,?,?,?,?,?,?,?)")
	if err != nil {
		return user, err
	}
	_, err = stmtIn.Exec(userBean.UserId, userBean.Account, userBean.Pwd, userBean.UserName, userBean.JobNumber, userBean.HeadPortrait, userBean.CredentialType, userBean.CredentialNumber, userBean.PhoneNumber)
	_ = stmtIn.Close()
	_, _ = FileTreeNodeCreate(userBean.UserId, "根目录", "0", false)
	_, _ = FileTreeNodeCreate(userBean.UserId+"-xmwj", "项目文件夹", userBean.UserId, false)
	_, _ = FileTreeNodeCreate(userBean.UserId+"-srwj", "私人文件夹", userBean.UserId, false)
	_, _ = FileTreeNodeCreate(userBean.UserId+"-wtwj", "委托文件夹", userBean.UserId, false)
	loge.WD(bean.NewSucceedMessage(userBean).GetJson())
	return UserSelect(userBean.Account)
}
func UserUpdate(userBean UserBean) error {
	if len(userBean.Account) == 0 {
		return bean.NewErrorMessage("账号不能为空")
		//return user, httpUtils.NewResultError(code.NormalErr, "账号不能为空")
	}
	user, err := UserSelect(userBean.Account)
	if err != nil {
		return err
	}
	if len(user.UserId) < 0 {
		return bean.NewErrorMessage("用户不存在!")
	}
	user.Modify(userBean)
	stmtIn, err := dbConn.Prepare("UPDATE table_user SET pwd=?,name=?,job_number=?,head_portrait=?,credential_type=?,credential_number=?,phone_number=? WHERE account=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(user.Pwd, user.UserName, user.Account, user.JobNumber, user.HeadPortrait, user.CredentialType, user.CredentialNumber, user.PhoneNumber)
	_ = stmtIn.Close()
	return err
}

func UserLogin(account, pwd string) (user UserBean, err error) {
	if len(account) == 0 {
		return user, bean.NewErrorMessage("登陆名字不能为空")
	}
	if len(pwd) == 0 {
		return user, bean.NewErrorMessage("密码不能为空")
	}
	user, err = UserSelect(account)
	if err != nil && len(user.UserId) <= 0 {
		return user, bean.NewErrorMessage("用户不存在或密码错误!")
	}
	if user.Pwd != pwd {
		return user, bean.NewErrorMessage("用户不存在或密码错误!")
	}
	return
}

func UserDelete(account string) error {
	if account == "admin" {
		return bean.NewErrorMessage("管理员不能为删除！")
	}
	userBean, _ := UserSelect(account)
	_ = FileTreeNodeDeleteAll(userBean.UserId)
	stmtDel, err := dbConn.Prepare("DELETE FROM table_user WHERE account=?")
	if err != nil {
		return err
	}
	_, err = stmtDel.Exec(account)
	_ = stmtDel.Close()

	return err
}
func UserSelect(account string) (UserBean, error) {
	var user UserBean
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_user WHERE account = ?")
	if err != nil {
		return user, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(account)
	if err != nil {
		return user, err
	}
	defer rows.Close()
	if rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return user, err
		}
		user = *NewUserBean(mapStrings)
		beans, _ := UserToStructureTreeSelect(user.UserId)
		user.Structures = &beans
	}
	return user, err
}
func UserSelectByUserId(userId string) (UserBean, error) {
	var user UserBean
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_user WHERE user_id = ?")
	if err != nil {
		return user, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(userId)
	if err != nil {
		return user, err
	}
	defer rows.Close()
	if rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return user, err
		}
		user = *NewUserBean(mapStrings)
		beans, _ := UserToStructureTreeSelect(user.UserId)
		user.Structures = &beans
	}
	return user, err
}

func UserSelectAll() ([]UserBean, error) {
	var userBeans = make([]UserBean, 0)
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_user")
	if err != nil {
		return userBeans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query()
	if err != nil {
		return userBeans, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return userBeans, err
		}
		userBean := *NewUserBean(mapStrings)
		beans, _ := UserToStructureTreeSelect(userBean.UserId)
		userBean.Structures = &beans
		userBeans = append(userBeans, userBean)
	}

	return userBeans, err
}

//todo 这里没有判断是否存在两个表,可能存在冗余数据
func UserToStructureTreeAdd(nodeId string, userId string) error {
	if len(nodeId) == 0 {
		return bean.NewErrorMessage("节点ID不能为空")
	}
	stmtIn, err := dbConn.Prepare("DELETE FROM table_tree_structure_user WHERE node_id=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(nodeId)
	if err != nil {
		return err
	}
	_ = stmtIn.Close()
	userIds := strings.Split(userId, ",")
	if len(userIds) == 0 {
		//return bean.NewErrorMessage("人员ID不能为空")
		return nil
	}
	stmtIn, err = dbConn.Prepare("REPLACE INTO table_tree_structure_user (node_id,user_id)VALUES(?,?)")
	if err != nil {
		return err
	}
	for _, v := range userIds {
		if len(v) != 0 {
			_, err = stmtIn.Exec(nodeId, v)
		}
	}
	if err != nil {
		return err
	}
	return nil
}

//查询组织机构中所有的人员
func UserToStructureTreeSelectAll(nodeId string) ([]UserBean, error) {
	beans := make([]UserBean, 0)
	if len(nodeId) == 0 {
		return beans, bean.NewErrorMessage("节点ID不能为空")
	}
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree_structure_user LEFT OUTER JOIN table_user ON table_tree_structure_user.user_id=table_user.user_id WHERE node_id=?")
	if err != nil {
		return beans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return beans, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return beans, err
		}
		user := *NewUserBean(mapStrings)
		beans = append(beans, user)
	}
	return beans, err
}
func UserToStructureTreeSelect(userId string) ([]StructureTreeBean, error) {
	beans := make([]StructureTreeBean, 0)
	if len(userId) == 0 {
		return beans, bean.NewErrorMessage("用户ID不能为空")
	}
	stmtOut, err := dbConn.Prepare(`SELECT * FROM table_tree_structure_user 
LEFT OUTER JOIN table_tree_structure ON table_tree_structure_user.node_id=table_tree_structure.node_id 
LEFT OUTER JOIN table_user tu on table_tree_structure.head_user_id = tu.user_id 
WHERE table_tree_structure_user.user_id=?`)
	if err != nil {
		return beans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(userId)
	if err != nil {
		return beans, err
	}
	defer rows.Close()
	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			return beans, err
		}
		user := NewStructureTreeBean(mapStrings)
		if len(user.NodeName) != 0 {
			beans = append(beans, user)
		}
	}
	return beans, err
}
